1
|
|
|
"use strict"; |
2
|
|
|
|
3
|
2 |
|
const requestPromise = require('request-promise-native'); |
4
|
2 |
|
const pkg = require('../../package.json'); |
5
|
2 |
|
const logger = require('../logger/taskLogger')('Client'); |
6
|
2 |
|
const Response = require('../model/Response'); |
7
|
|
|
|
8
|
2 |
|
const defaultOptionList = { |
9
|
|
|
headers: {'User-Agent': pkg.name}, |
10
|
|
|
json: true, |
11
|
|
|
simple: false, |
12
|
|
|
resolveWithFullResponse: true |
13
|
|
|
}; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @param {Request} request |
17
|
|
|
* |
18
|
|
|
* @returns {Promise<Response|Error>} |
19
|
|
|
*/ |
20
|
2 |
|
module.exports = request => { |
21
|
|
|
const optionList = Object.assign( |
22
|
|
|
{}, |
23
|
|
|
defaultOptionList, |
24
|
|
|
{ |
25
|
|
|
uri: request.getUri(), |
26
|
|
|
method: request.getMethod(), |
27
|
|
|
headers: Object.assign({}, defaultOptionList.headers, request.getHeaders()), |
28
|
|
|
json: request.isJson() |
29
|
|
|
} |
30
|
|
|
); |
31
|
|
|
|
32
|
7 |
|
if (request.getForm() && Object.keys(request.getForm()).length > 0) { |
33
|
1 |
|
optionList.form = request.getForm(); |
34
|
|
|
} |
35
|
7 |
|
if (request.getPayload() && Object.keys(request.getPayload()).length > 0) { |
36
|
1 |
|
optionList.body = request.getPayload(); |
37
|
|
|
} else { |
38
|
6 |
|
optionList.body = optionList.json === true ? {} : ''; |
39
|
|
|
} |
40
|
7 |
|
if (request.getQueryString() && Object.keys(request.getQueryString()).length > 0) { |
41
|
1 |
|
optionList.qs = request.getQueryString(); |
42
|
|
|
} else { |
43
|
6 |
|
optionList.qs = optionList.json === true ? {} : null; |
44
|
|
|
} |
45
|
|
|
|
46
|
7 |
|
const transformResponseToResponseObject = response => { |
47
|
|
|
return new Response( |
48
|
|
|
response.body, |
49
|
|
|
response.statusCode, |
50
|
|
|
response.headers, |
51
|
|
|
request |
52
|
|
|
); |
53
|
|
|
}; |
54
|
|
|
|
55
|
7 |
|
const transformErrorToResponseObject = error => { |
56
|
|
|
logger.debug('[Error] Conversion to Response.', {options: optionList}); |
57
|
|
|
|
58
|
2 |
|
return Promise.resolve(new Response( |
59
|
|
|
optionList.json === true ? { |
60
|
|
|
error: error.error.code, |
61
|
|
|
message: error.message |
62
|
|
|
} : `${error.error.code} ${error.message}`, |
63
|
|
|
500, |
64
|
|
|
{}, |
65
|
|
|
request |
66
|
|
|
)); |
67
|
|
|
}; |
68
|
|
|
|
69
|
7 |
|
const logResponseObject = response => { |
70
|
|
|
logger.debug('[Reponse]', {response: response, options: optionList}); |
71
|
|
|
|
72
|
7 |
|
return response; |
73
|
|
|
}; |
74
|
|
|
|
75
|
7 |
|
logger.debug('[Request]', {options: optionList}); |
76
|
|
|
|
77
|
7 |
|
const transform = requestPromise(optionList) |
78
|
|
|
.then(transformResponseToResponseObject, transformErrorToResponseObject); |
79
|
|
|
|
80
|
7 |
|
return transform |
81
|
|
|
.then(logResponseObject); |
82
|
|
|
}; |
83
|
|
|
|